/*
 * view.c
 *
 *  Created on: Aug 21, 2009
 *      Author: jacky
 */
#include <stdio.h>
#include "core.h"

void render(HttpRequest*req, HttpResponse *rsp)
{
	FILE *fp;
	char parameter[256]="";

	rsp->autoRender = 0; // if we do render not need do auto render again.
	if (!rsp->Out || rsp->Out != stdout)
	{
		fp = rsp->Out;
		rsp->Out = stdout;
	}

	// start render header.
	if (rsp->status)
	{
//		fprintf(rsp->Out, "Status %d\r\n", rsp->status);
		fprintf(rsp->Out, "Status: %d\r\n", rsp->status);
		if(NULL != rsp->extra_header)
		{
			fprintf(rsp->Out,"%s\r\n",rsp->extra_header);
		}
	}

	if (NULL == rsp->contentType)
	{
		rsp->contentType = "text/html";
	}

	if (NULL != rsp->charset)
	{
		snprintf(parameter, sizeof(parameter), "; charset=%s", rsp->charset);
	}

	fprintf(rsp->Out, "Content-Type: %s%s\r\n", rsp->contentType, parameter);
	fprintf(rsp->Out, "\r\n"); // http header end.
	// start render content.
	if (NULL != rsp->layout)
	{
		(void) (rsp->layout)(req, rsp);
	}
	else if (NULL != rsp->view)
	{
		DEBUG_PRINTF("%s: %s() LINE[%d]\n",__FILE__, __FUNCTION__, __LINE__); /* TODO:Jacky debug */
		(void) (rsp->view)(req, rsp);
	}
}
